﻿using Pay.Core;
using Pay.Data;
using Pay.DTO;
using Pay.IService;
using Pay.Service.Cache;
using Pay.TO;
using System;
using System.Collections.Generic;
using System.Data.Entity.SqlServer;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Pay.Service {
    public class UserRedTransferService : ServiceBase, IUserRedTransferService, IDisposable {
        private IUnitOfWork _iUnitOfWork;
        private ISettingService _settingService;
        private IMerchantBankCardService _iMerchantBankCardService;
        private IMerchantService _merchantService;
        public UserRedTransferService(IUnitOfWork iUnitOfWork, ISettingService settingService, IMerchantBankCardService iMerchantBankCardService, IMerchantService merchantService) : base(iUnitOfWork) {
            _iUnitOfWork = iUnitOfWork;
            _settingService = settingService;
            _iMerchantBankCardService = iMerchantBankCardService;
            _merchantService = merchantService;
        }

        private static readonly object objkey = new object();

        /// <summary>
        /// 用户红钻转赠
        /// </summary>
        /// <param name="model"></param>
        /// <param name="userId"></param>
        /// <returns></returns>
        public bool UserRedTransfer(user_red_transfer_model model, long userId, bool isBackstage = false, bool IsShowTransferOut = true) {
            lock (objkey) {
                if (!isBackstage) {
                    var member = _merchantService.GetTokenUser(userId);
                    if (member.disabled) {
                        throw new ServerErrorException("您的账号已被禁用，不能进行转钻");
                    }
                    if (!member.is_verify_no_card) {//实名认证未通过
                        throw new ServerErrorException("您的账号实名认证未通过，请等待实名认证通过再进行转钻操作");
                    }
                    if (!member.is_face) {
                        throw new ServerErrorException("请先到我的设置进行人脸认证在进行转钻操作");
                    }
                }
                if (string.IsNullOrEmpty(model.receiver_mobile))
                    throw new ServerErrorException("请输入对方账号");
                var oem = context.Merchants.FirstOrDefault(c => c.MerchantNo == t_RequestMethod.merchant_no);
                Merchant receiver = context.Merchants.FirstOrDefault(c => c.Mobile == model.receiver_mobile && c.IsOEM == false && c.OemId == oem.Id);//收钻方
                if (receiver == null)
                    throw new ServerErrorException("对方账号不存在");
                if (model.amount < 10)
                    throw new ServerErrorException("转赠数量至少为10个");
                token_transfer_setting transfer_setting = _settingService.GetTokenSetting().token_transfer;
                if (transfer_setting == null)
                    throw new ServerErrorException("后台未进行转赠费率设置");
                Merchant user = context.Merchants.FindById(userId);//转钻方
                if (!isBackstage) {
                    if (user != null && user.Password != WebHelper.GetPasswrodWithTwiceEncode(model.password, user.PasswordSalt))
                        throw new ServerErrorException("登录密码不正确");
                    var receiverAuth = _merchantService.GetAuth(receiver.Id);
                    if (receiverAuth == null || receiverAuth.account_name != model.receiver_name)
                        throw new ServerErrorException("对方账号与姓名不匹配");
                }
                //if (!isBackstage) {
                //    //判断 是否绑定银行卡 未绑定银行卡不允许转钻
                //    var bankCard = _iMerchantBankCardService.GetBankCardByMerchantId(userId);
                //    if (bankCard == null)
                //        throw new ServerErrorException("您未绑定银行卡，不能进行转钻，请使用最新版本APP，到“我的->账号设置->银行卡管理”中进行绑定");
                //    else if (bankCard.status == EMerchantBankCardStatus.ToAudit)
                //        throw new ServerErrorException("您的银行卡信息正在审核中，不能进行转钻，请耐心等待");
                //    else if (bankCard.status == EMerchantBankCardStatus.AuditFail)
                //        throw new ServerErrorException("您的银行卡信息审核未通过，不能进行转钻，请到“我的->账号设置->银行卡管理”中进行重新提交");
                //}
                //if (user.Mobile == "13860226988")
                //    throw new ServerErrorException("当前账号不允许转钻");
                //var specialUser = context.Merchants.FirstOrDefault(c => c.Mobile == "13860226988" && c.IsOEM == false && c.OemId == oem.Id);
                //if (specialUser != null) {
                //    var parents = _merchantService.GetParents(user.Id, false);
                //    if (parents.Any(c => c.id == specialUser.Id)) {
                //        if (receiver.Id != specialUser.Id) {
                //            throw new ServerErrorException("当前账号只能转钻给指定账号：13860226988");
                //        }
                //    }
                //}
                using (var trans = context.Database.BeginTransaction())//防止重复读
                {
                    try {
                        decimal fee = (model.amount * transfer_setting.transfer_fee_rate).NumberToFixedNoRound(6);
                        RedRecord userRedRecord = context.RedRecord.Where(o => o.MerchantId == user.Id).FirstOrDefault();
                        if ((userRedRecord.TotalRedDrill - userRedRecord.ConsumeRedDrill) < (model.amount + fee))
                            throw new ServerErrorException("可转赠数量不足");

                        //增加转赠记录
                        UserRedTransferHis userRedTransferHis =
                            new UserRedTransferHis() {
                                UserId = user.Id,
                                ReceiveUserId = receiver.Id,
                                Amount = model.amount,
                                FeeRate = transfer_setting.transfer_fee_rate,
                                Fee = model.amount * transfer_setting.transfer_fee_rate,
                                CreateTime = DateTime.Now.ToUnix(),
                                IsShowTransferOut = IsShowTransferOut
                            };
                        userRedTransferHis = context.UserRedTransferHis.Add(userRedTransferHis);
                        _iUnitOfWork.Commit();

                        //扣除转钻方红钻数
                        userRedRecord.ConsumeRedDrill += (model.amount + fee);

                        //增加收钻方红钻数
                        RedRecord receiverRedRecord = context.RedRecord.Where(o => o.MerchantId == receiver.Id).FirstOrDefault();
                        if (receiverRedRecord == null)
                            throw new ServerErrorException("对方账号不存在");
                        receiverRedRecord.TotalRedDrill += model.amount;

                        //创建分润记录
                        if (user.ParentId != 0) {//上一级用户
                            var firstUser = _merchantService.Get(user.ParentId);//上一级用户
                            RedRecord firstRedRecord = context.RedRecord.Where(o => o.MerchantId == firstUser.id).FirstOrDefault();
                            UserRedTransferBenefit firstBenefit = new UserRedTransferBenefit() {
                                TransferId = userRedTransferHis.Id,
                                BenefitUserId = firstUser.id,
                                BenefitRate = transfer_setting.first_user_benefit_rate,
                                Amount = fee * transfer_setting.first_user_benefit_rate
                            };

                            if (firstBenefit.Amount.NumberToFixedNoRound(6) > 0) {
                                context.UserRedTransferBenefit.Add(firstBenefit);
                                //更新红钻总数
                                firstRedRecord.TotalRedDrill += firstBenefit.Amount;
                            }

                            if (firstUser.parent_id != 0) {//上二级用户
                                var secondUser = _merchantService.Get(firstUser.parent_id);//上二级用户
                                RedRecord secondRedRecord = context.RedRecord.Where(o => o.MerchantId == secondUser.id).FirstOrDefault();
                                UserRedTransferBenefit secondBenefit = new UserRedTransferBenefit() {
                                    TransferId = userRedTransferHis.Id,
                                    BenefitUserId = secondUser.id,
                                    BenefitRate = transfer_setting.second_user_benefit_rate,
                                    Amount = fee * transfer_setting.second_user_benefit_rate
                                };
                                if (secondBenefit.Amount.NumberToFixedNoRound(6) > 0) {
                                    context.UserRedTransferBenefit.Add(secondBenefit);
                                    //更新红钻总数
                                    secondRedRecord.TotalRedDrill += secondBenefit.Amount;
                                }
                            }
                        }

                        _iUnitOfWork.Commit("RedRecord" + userId, "RedRecord" + receiver.Id);
                        trans.Commit();
                        return true;
                    } catch (ServerErrorException ex) {
                        trans.Rollback();
                        throw ex;
                    } catch (Exception ex) {
                        trans.Rollback();
                        throw ex;
                    }
                }
            }
        }
    }
}